<template>
  <div v-show="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <EditDropDown dropdownTitle="设备信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="8">
                <EquipClassSelect
                  :isDisabled="drawerType === 'exception'"
                  :isRequired="true"
                  :className="formValue.className"
                  @changeClassName="changeClassName"
                />
              </px-col>
              <px-col :span="8">
                <EquipSystemTree
                  :isDisabled="drawerType === 'exception'"
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCode="formValue.systemVal"
                  propValue="systemVal"
                  @changeAllSystemCodes="changeAllSystemCodes"
                  @changeSystemCodes="changeSystemCodes"
                  @clearSystem="clearSystem"
                />
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备编号" prop="eqpId">
                  <px-input
                    v-model="formValue.eqpId"
                    placeholder="请点击选择"
                    maxlength="50"
                    disabled
                    style="width: calc(100% - 108px); margin-right: 8px"
                  />
                  <px-button type="primary" plain style="width: 100px" @click="dialogVisible = true">选择设备</px-button>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备名称" prop="eqpName">
                  <px-input v-model="formValue.eqpName" placeholder="选择设备编号后自动带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="设备位置" prop="eqpPosition">
                  <px-input v-model="formValue.eqpPosition" placeholder="选择设备编号后自动带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="报修内容">
          <template v-slot:content>
            <px-row style="width: 100%">
              <px-col :span="8">
                <px-form-item label="维修任务名称" prop="workOrderName">
                  <px-input v-model="formValue.workOrderName" placeholder="请输入维修任务名称" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="维修任务编号" prop="workOrderCode">
                  <px-input v-model="formValue.workOrderCode" disabled placeholder="自动生成" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="故障类型" prop="faultType">
                  <px-cascader
                    ref="cascaderRef"
                    v-model="formValue.faultType"
                    style="width: 100%"
                    :props="{ value: 'faultTypeCode', label: 'name', checkStrictly: true }"
                    :options="shareData.faultTypeList"
                    placeholder="请选择故障类型"
                    clearable
                    filterable
                    @change="handleTypeChange"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="维修需求来源" prop="maintenanceSource">
                  <px-select
                    v-model="formValue.maintenanceSource"
                    :disabled="drawerType === 'exception'"
                    placeholder="请选择维修需求来源"
                    filterable
                    @change="handleSourceChange"
                  >
                    <px-option v-for="item in shareData.faultSourceList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="关联单号" prop="relatedOrderNum">
                  <px-input
                    v-if="sourceType === 'OTHER'"
                    v-model="formValue.relatedOrderNum"
                    maxlength="50"
                    placeholder="请输入关联单号"
                    :disabled="!formValue.maintenanceSource"
                    clearable
                  />
                  <px-select
                    v-else
                    v-model="formValue.relatedOrderNum"
                    :disabled="!formValue.maintenanceSource || drawerType === 'exception'"
                    placeholder="请选择关联单号"
                    clearable
                    filterable
                  >
                    <px-option v-for="item in []" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="故障等级" prop="faultLevel">
                  <px-select v-model="formValue.faultLevel" placeholder="请选择故障等级" filterable clearable>
                    <px-option v-for="item in shareData.faultLevelList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="16">
                <px-form-item label="故障描述" prop="faultDesc">
                  <px-input
                    v-model="formValue.faultDesc"
                    type="textarea"
                    placeholder="请输入故障描述"
                    :autosize="{ minRows: 1, maxRows: 4 }"
                    maxlength="1000"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="是否需要停机" prop="isStop">
                  <px-radio-group v-model="formValue.isStop">
                    <px-radio :label="1">是</px-radio>
                    <px-radio :label="0">否</px-radio>
                  </px-radio-group>
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="故障图片" prop="repairImageList">
                  <PhotoUpload
                    v-if="!isMain && !isView"
                    :photoType="photoType"
                    :photoData="{ moduleName: moduleName }"
                    :photoList="formValue.repairImageList"
                    style="margin-bottom: 18px"
                    @changePhotoList="changePhotoList"
                    @savePhotoStatus="savePhotoStatus"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="维修措施/建议">
          <template v-slot:content>
            <px-row style="width: 100%">
              <px-col :span="24">
                <px-form-item label="维修措施/建议" prop="maintenanceAdvice">
                  <px-input
                    v-model="formValue.maintenanceAdvice"
                    type="textarea"
                    placeholder="请输入维修措施/建议"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    maxlength="1000"
                    clearable
                  />
                </px-form-item>
              </px-col>
              <!-- TODO sop接口不满足，待提供 -->
              <!-- <px-col :span="24">
                <px-form-item label="关联SOP" prop="maintenanceAdvice">
                  <px-table :data="fileTableData" class="equip-table" size="small" max-height="400" border>
                    <px-table-column
                      v-for="(item, index) in fileTableColumns"
                      :key="index"
                      :label="item.label"
                      :min-width="item.minWidth"
                      :align="item.align"
                      :show-overflow-tooltip="item.showOverflowTooltip"
                      :fixed="item.fixed"
                    >
                      <template #default="scope">
                        <span v-if="item.type === 'size'">
                          {{ scope.row.fileSize !== null ? byteToMb(scope.row.fileSize) : "" }}
                        </span>
                        <span v-else>
                          {{ scope.row[item.prop] === 0 ? scope.row[item.prop] : scope.row[item.prop] ? scope.row[item.prop] : "-" }}
                        </span>
                      </template>
                    </px-table-column>
                    <px-table-column fixed="right" label="操作" min-width="160" align="center">
                      <template #default="scope">
                        <px-tooltip content="查看" placement="top">
                          <px-button link type="primary" icon="Tickets" @click="handleView(scope.row)" />
                        </px-tooltip>
                        <px-tooltip content="下载" placement="top">
                          <px-button link type="primary" icon="Download" @click="handleDownload(scope.row)" />
                        </px-tooltip>
                        <px-tooltip content="移除" placement="top">
                          <px-button link type="primary" icon="Remove" @click="removeFile(scope.$index)" />
                        </px-tooltip>
                      </template>
                    </px-table-column>
                  </px-table>
                  <px-button icon="Plus" block type="primary" @click="isFileDialogShow = true">关联SOP</px-button>
                </px-form-item>
              </px-col> -->
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="派工信息">
          <template v-slot:content>
            <px-row style="width: 100%">
              <px-col :span="8">
                <px-form-item label="计划维修时间" prop="maintenancePlanTime">
                  <px-date-picker
                    v-model="formValue.maintenancePlanTime"
                    value-format="YYYY-MM-DD"
                    type="date"
                    :disabled-date="disabledDate"
                    placeholder="请选择日期"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="维修组" prop="opsGroupCode">
                  <px-select
                    v-model="formValue.opsGroupCode"
                    placeholder="请选择维修组"
                    filterable
                    clearable
                    :disabled="!formValue.className"
                    @focus="handleGroupFocus"
                    @change="handleGroupChange"
                  >
                    <px-option v-for="item in groupList" :key="item.code" :label="item.name" :value="item.code" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="维修组成员" prop="opsGroupMember">
                  <px-input v-model="formValue.opsGroupMember" disabled placeholder="根据维修组获取" maxlength="50" />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="四级主管审批" prop="isApproval">
                  <px-radio-group v-model="formValue.isApproval" :disabled="formValue.workOrderStatus === 2">
                    <px-radio :label="0">无需审批，仅通知</px-radio>
                    <px-radio :label="1">需要审批</px-radio>
                  </px-radio-group>
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="四级主管" prop="approverId">
                  <px-select-v2
                    v-model="formValue.approverId"
                    filterable
                    clearable
                    :options="approvalList"
                    placeholder="请选择四级主管"
                    @change="approvalIdChange"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" plain :disabled="photoStatusFlag" @click="handleSubmit(formRef, 'draft')">保存草稿</px-button>
      <px-button v-if="formValue.isApproval === 1" type="primary" :disabled="photoStatusFlag" @click="handleSubmit(formRef)">提交审批</px-button>
      <px-button v-else type="primary" :disabled="photoStatusFlag" @click="handleSubmit(formRef)">发布维修任务</px-button>
    </div>
    <FileDialog :visible="isFileDialogShow" @closeDialog="isFileDialogShow = false" @addFileDialog="addFileDialog" />
    <!-- 文件详情 -->
    <FileDetail v-model:visible="fileDetailVisible" :fileDetailData="fileDetailData" />
    <!-- 选择设备弹窗 -->
    <EquipIdSelectDialog
      :visible="dialogVisible"
      :className="formValue.className"
      :systemCodes="systemCodes"
      @closeEquipDialog="closeEquipDialog"
      @changeEqpId="changeEqpId"
    />
  </div>
</template>
<script setup lang="ts">
// import { queryEquipLedger } from "@/api/equip/archive";
import { changeExceptionTaskStatus, detailExceptionTask } from "@/api/equip/exception";
import {
  addMaintainDraft,
  addMaintainList,
  detailMaintainList,
  editMaintainDraft,
  editMaintainList,
  getModuleName,
  getOpsGroupList,
  getOpsGroupMember,
  getWorkOrderCode
} from "@/api/equip/maintain";
import FileDetail from "@/views/all/knowledge/documentManage/component/fileDetail.vue";

import { fileDetailAPI } from "@/api/knowledge/documentManage";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipIdSelectDialog from "@/views/all/equip/components/EquipIdSelectDialog.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, getCurrentInstance, reactive, ref, toRefs, watch } from "vue";
import FileDialog from "./FileDialog.vue";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "shareData", "taskId", "orderCode", "workOrderCode"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const formRef = ref();
const cascaderRef = ref();
const state = reactive<any>({
  isFileDialogShow: false,
  formValue: {
    className: "",
    systemVal: "",
    eqpId: "",
    eqpName: ""
  },
  photoType: "add",
  moduleName: "",
  photoStatusFlag: false,
  sourceType: "",
  eqpList: [],
  approvalList: [],
  fileTableColumns: [
    { prop: "name", label: "文件名称", minWidth: "180", showOverflowTooltip: true },
    { prop: "fileSize", label: "文档大小(M)", minWidth: "140", type: "size", showOverflowTooltip: true },
    { prop: "updateTime", label: "修改时间", minWidth: "140", showOverflowTooltip: true },
    { prop: "updateByName", label: "修改人", minWidth: "140", showOverflowTooltip: true }
  ],
  fileTableData: [],
  groupList: [], // 运维组列表
  fileDetailVisible: false,
  fileDetailData: {},
  systemCodes: [],
  dialogVisible: false
});
const {
  formValue,
  photoType,
  isFileDialogShow,
  moduleName,
  photoStatusFlag,
  sourceType,
  eqpList,
  approvalList,
  fileTableColumns,
  fileTableData,
  fileDetailVisible,
  fileDetailData,
  groupList,
  systemCodes,
  dialogVisible
} = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  eqpId: [{ required: true, message: "设备编号不能为空", trigger: "blur" }],
  workOrderName: [{ required: true, message: "维修任务名称不能为空", trigger: "blur" }],
  faultType: [{ required: true, message: "故障类型不能为空", trigger: "blur" }],
  maintenanceSource: [{ required: true, message: "故障来源不能为空", trigger: "blur" }],
  faultLevel: [{ required: true, message: "故障等级不能为空", trigger: "blur" }],
  isStop: [{ required: true, message: "是否需要停机不能为空", trigger: "blur" }],
  faultDesc: [{ required: true, message: "故障描述不能为空", trigger: "change" }],
  alarmStock: [{ required: true, message: "故障图片不能为空", trigger: "blur" }],
  maintenancePlanTime: [{ required: true, message: "计划维修时间不能为空", trigger: "blur" }],
  opsGroupCode: [{ required: true, message: "维修组不能为空", trigger: "blur" }],
  isApproval: [{ required: true, message: "请选择是否需要四级主管审批", trigger: "blur" }],
  approverId: [{ required: true, message: "四级主管审批不能为空", trigger: "blur" }]
}));

// 获取后端自动生成的工单号
const getToolCode = async () => {
  const data = await getWorkOrderCode();
  formValue.value.workOrderCode = data;
};

const byteToMb = bytes => {
  return (bytes / 1024 / 1024).toFixed(2);
};

const { proxy } = getCurrentInstance();
// 下载
const handleDownload = row => {
  (proxy as any).download("post", "/dms/api/v1/doc/download", { id: [row.id] }, row.name);
};

const removeFile = index => {
  fileTableData.value.splice(index, 1);
};

// 文件详情
const handleView = async row => {
  state.fileDetailData = await fileDetailAPI({ id: row.id });
  state.fileDetailVisible = true;
};

const disabledDate = (time: Date) => {
  return time.getTime() < Date.now() - 8.64e7;
};

const handleSourceChange = val => {
  sourceType.value = val;
};
// 获取运维组列表数据
const handleGroupFocus = async () => {
  groupList.value = await getOpsGroupList({ className: formValue.value.className });
};
// 根据运维组列表拿到对应的人员信息
const handleGroupChange = async val => {
  if (val) {
    const id = groupList.value.find(item => item.code === val)?.id;
    const list = await getOpsGroupMember(id);
    formValue.value.opsGroupMember = list.map(item => item.operateName)?.join(";");
  }
};

const addFileDialog = val => {
  if (val) {
    fileTableData.value = fileTableData.value?.concat(val)?.filter((obj, index, self) => {
      return self.map(x => x.id).indexOf(obj.id) === index;
    });
  }
};
const handleGetApprovalList = async () => {
  approvalList.value = await getEmployeeIdAndName();
};

// 获取借用人的名字
const approvalIdChange = val => {
  const arr = approvalList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.approverName = arr[0].label;
  }
};

const getExceptionDetail = async () => {
  const res = await detailExceptionTask(props.orderCode);
  const { systemCode, className, eqpId, eqpName, positionName } = res;
  formValue.value = {
    maintenanceSource: "POINTCHECK",
    relatedOrderNum: props.orderCode,
    systemVal: systemCode,
    className,
    eqpId,
    eqpName,
    eqpPosition: positionName
  };
};
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value.resetFields();
    getModuleNameValue();
    handleGetApprovalList();
    if (props.drawerType === "add") {
      getToolCode();
      photoType.value = "add";
    } else if (props.drawerType === "edit") {
      getDetail();
      // TODO sop接口不满足，待提供
      // getSopDetail();
      photoType.value = "edit";
    } else if (props.drawerType === "exception") {
      photoType.value = "add";
      await getExceptionDetail();
      getToolCode();
    }
  } else {
    formValue.value = {
      className: "",
      systemVal: "",
      eqpId: "",
      eqpName: ""
    };
  }
});
// 获取getModuleName
const getModuleNameValue = async () => {
  const data = await getModuleName();
  moduleName.value = data;
};
// TODO sop接口不满足，待提供
// const getSopDetail = async () => {
//   const { workOrderCode } = props;
//   if (workOrderCode) {
//     const params = {
//       workOrderCode
//     };
//     const data = await viewMaintainFileList(params);
//     fileTableData.value = data;
//   }
// };
// 获取详情接口
const getDetail = async () => {
  const params = {
    id: props.taskId
  };
  const data = await detailMaintainList(params);
  const { systemCode, opsGroupNameDTO, maintenancePlanTime } = data;
  formValue.value = data;
  handleGroupFocus();
  formValue.value.systemVal = systemCode;
  formValue.value.opsGroupCode = opsGroupNameDTO?.code;
  if (opsGroupNameDTO && opsGroupNameDTO.opsOperateList && opsGroupNameDTO.opsOperateList?.length !== 0) {
    formValue.value.opsGroupMember = opsGroupNameDTO.opsOperateList?.map(item => item.operateName)?.join(";");
  }
  formValue.value.maintenancePlanTime = maintenancePlanTime ? `${maintenancePlanTime} 00:00:00` : "";
  if (data?.repairImageList && data?.repairImageList?.length > 0) {
    data.repairImageList?.forEach(item => {
      item.url = item.fileUrl;
    });
    formValue.value.repairImageList = data.repairImageList;
  } else {
    formValue.value.repairImageList = [];
  }
};
// 返回主页面
const backMainPage = () => {
  PxMessageBox.confirm(`确认退出工单吗？退出后内容将不会保存，请谨慎操作`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      formRef.value.resetFields();
      fileTableData.value = [];
      emits("backMainPage");
    })
    .catch(() => {});
};
// 新的图片列表
const changePhotoList = val => {
  formValue.value.repairImageList = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};

// TODO sop接口不满足，待提供
// const saveFile = async () => {
//   const bizIds = fileTableData.value?.map(item => item.id);
//   const res = await addMaintainFileList({ workOrderCode: formValue.value.workOrderCode, bizIds });
//   if (res) {
//     PxMessage.success("关联SOP成功");
//   }
// };
// 提交
const handleSubmit = async (formEl: any, type?: any) => {
  if (!formEl) return;
  const params = formValue.value;
  const imgList = [];
  const { systemVal, faultType, repairImageList } = formValue.value;
  if (repairImageList && repairImageList?.length > 0) {
    repairImageList?.forEach(item => {
      if (item?.id) {
        imgList.push(item.id);
      } else if (item?.response.data.id) {
        imgList.push(item.response.data.id);
      }
    });
  }

  params.faultType = Array.isArray(faultType) ? faultType[faultType?.length - 1] : faultType;
  params.systemCode = systemVal;
  // 保存草稿不需要对数据进行校验
  if (type === "draft") {
    console.log("保存草稿");
    if (props.drawerType === "add") {
      await addMaintainDraft({ ...params, repairImageList: imgList });
      // TODO sop接口不满足，待提供
      // await saveFile();
      PxMessage.success("保存草稿成功");
      emits("backMainPage");
      emits("queryTable");
    } else if (props.drawerType === "edit") {
      await editMaintainDraft({ id: props.taskId, ...params, repairImageList: imgList });
      PxMessage.success("编辑草稿成功");
      // TODO sop接口不满足，待提供
      // await saveFile();
      emits("backMainPage");
      emits("queryTable");
    }
  } else {
    await formEl.validate(async valid => {
      if (valid) {
        if (props.drawerType === "add" || props.drawerType === "exception") {
          await addMaintainList({ ...params, repairImageList: imgList });
          PxMessage.success("创建成功");
          // TODO sop接口不满足，待提供
          // await saveFile();
          if (props.drawerType === "exception") {
            await changeExceptionTaskStatus(formValue.value.relatedOrderNum);
          }
          emits("backMainPage");
          emits("queryTable");
        } else if (props.drawerType === "edit") {
          await editMaintainList({ id: props.taskId, ...params, repairImageList: imgList });
          // TODO sop接口不满足，待提供
          // await saveFile();
          PxMessage.success("编辑成功");
          emits("backMainPage");
          emits("queryTable");
        }
      }
    });
  }
};

const handleTypeChange = () => {
  cascaderRef.value.togglePopperVisible();
};
// 关闭子级设备dialog弹窗
const closeEquipDialog = () => {
  dialogVisible.value = false;
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  systemCodes.value = [];
  if (!isOnlyClass) {
    formRef.value?.resetFields(["systemVal", "eqpId", "eqpName"]);
    formValue.value.opsGroupCode = "";
  }
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  formValue.value.className = val2;
  formValue.value.systemVal = val3;
  systemCodes.value = val4;
  formRef.value?.resetFields(["eqpId", "eqpName"]);
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  formValue.value.systemVal = val;
  systemCodes.value = val2;
  formRef.value?.resetFields(["eqpId", "eqpName"]);
};
// 系统组件值改变触发
const clearSystem = val => {
  systemCodes.value = [];
  formRef.value?.resetFields(["systemVal", "eqpId", "eqpName"]);
  formValue.value.eqpPosition = "";
};
// 改变设备编号
const changeEqpId = equipDetail => {
  formValue.value.className = equipDetail?.className || "";
  formValue.value.systemVal = equipDetail?.systemCode || "";
  systemCodes.value = [];
  formValue.value.eqpId = equipDetail?.eqpId || "";
  formValue.value.eqpName = equipDetail?.eqpName || "";
  formValue.value.eqpPosition = equipDetail?.positionNameAll || "";
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
